import React, {Component} from 'react'
import classNames from 'classnames'
import {isObject} from '../../utils'

export declare type ColumnProps =
  | string
  | boolean
  | number
  | {
      size?: boolean | number | string
      push?: string | number
      pull?: string | number
      offset?: string | number
      order?: string | number
    }

interface ColProps {
  xs?: ColumnProps
  sm?: ColumnProps
  md?: ColumnProps
  lg?: ColumnProps
  xl?: ColumnProps
  className?: string
  attributes?: any
}

class Col extends Component<ColProps> {
  getColumnSizeClass = (isXs: boolean, colWidth: string, colSize: string): string => {
    if (colSize === '') {
      return isXs ? 'col' : `col-${colWidth}`
    } else if (colSize === 'auto') {
      return isXs ? 'col-auto' : `col-${colWidth}-auto`
    }
    return isXs ? `col-${colSize}` : `col-${colWidth}-${colSize}`
  }

  getColClasses = (): string[] => {
    const {attributes} = this.props
    const colClasses: string[] = []
    const colWidths = ['xs', 'sm', 'md', 'lg', 'xl']

    colWidths.forEach((colWidth, i) => {
      let columnProp = (this.props as any)[colWidth]
      if (attributes) {
        delete attributes[colWidth]
      }

      if (!columnProp && columnProp !== '') {
        return
      }

      const isXs: boolean = i === 0

      if (isObject(columnProp)) {
        const colSizeInterfix = isXs ? '-' : `-${colWidth}-`
        const colClass = this.getColumnSizeClass(isXs, colWidth, columnProp.size)

        colClasses.push(
          classNames({
            [colClass]: columnProp.size || columnProp.size === '',
            [`order${colSizeInterfix}${columnProp.order}`]:
              columnProp.order || columnProp.order === 0,
            [`offset${colSizeInterfix}${columnProp.offset}`]:
              columnProp.offset || columnProp.offset === 0,
          }),
        )
      } else {
        const colClass = this.getColumnSizeClass(isXs, colWidth, columnProp)
        colClasses.push(colClass)
      }
    })

    if (!colClasses.length) {
      colClasses.push('col')
    }
    return colClasses
  }

  render() {
    const {className, attributes, children} = this.props
    const resultClassName = classNames(className, this.getColClasses())
    return (
      <div {...attributes} className={resultClassName}>
        {children}
      </div>
    )
  }
}

export default Col
